package com.qfedu.service.Impl;


import com.qfedu.fmmall.beans.Orders;
import com.qfedu.fmmall.beans.ProductSku;
import com.qfedu.fmmall.beans.ShoppingCartVo;
import com.qfedu.service.OrderSubmitService;
import com.qfedu.service.feign.OrderAddClient;
import com.qfedu.service.feign.OrderItemAddClient;
import com.qfedu.service.feign.ShopCatDelClient;
import com.qfedu.service.feign.StockUpdateClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class OrderSubmitServiceImpl implements OrderSubmitService {

    @Autowired
    private OrderAddClient orderAddClient;

    @Autowired
    private OrderItemAddClient orderItemAddClient;

    @Autowired
    private StockUpdateClient stockUpdateClient;

    @Autowired
    private ShopCatDelClient shopCatDelClient;

    @Override
    public Map<String, String> addOrder(String cids, Orders order) {
        Map<String,String> map = null;

        //1.保存订单（校验库存）order-add
        String orderId = UUID.randomUUID().toString().replace("-", "");
        order.setOrderId(orderId);
        List<ShoppingCartVo> carts = orderAddClient.saveOrder(order, cids);

        //2.保存订单快照 orderitem-add
        if(carts != null){
            int i = orderItemAddClient.addOrderItem(carts, orderId);
            System.out.println(i);

            if(i>0){
                //3.修稿库存
//                将购物车中的商品，及要修改的的库存 封装到productSku中
                List<ProductSku> skus = new ArrayList<>();
                for(ShoppingCartVo sc : carts){
                    String skuId = sc.getSkuId();
                    int newStock = sc.getSkuStock() - Integer.parseInt(sc.getCartNum());

                    ProductSku productSku = new ProductSku();
                    productSku.setSkuId(skuId);
                    productSku.setStock(newStock);
                    skus.add(productSku);
                }
                int j = stockUpdateClient.update(skus);
                //4。删除购物车
                if(j>0){
                    int k = shopCatDelClient.delete(cids);
                    if(k>0){
                        map = new HashMap<>();
                        map.put("orderId",orderId);
                        String str = "";
                        for (int index = 0; index < carts.size(); index++) {
                            str += carts.get(index).getProductName();
                            str = index == carts.size() - 1 ?str:str+",";
                        }
                        map.put("productNames",str);
                    }


                }
            }
        }


        return map;
    }
}
